package intf;

import java.io.*;
import java.util.Random;
import ctrl.Control;

public class AdHoc {

	static Control gui;

	public AdHoc(Control g) {
		gui = g;
	}

	public int create(String SSID, String key, String createButtonTxt) {
		String OS = System.getProperty("os.name").toLowerCase();
		// This section is for MAC. Will run shell command that will run the
		// Apple script that creates and disconnects from the Adhoc Network
		// Currently only works for OSX 10.8.2
		if (OS.indexOf("mac") >= 0) {
			System.out.println("$$ IfMgt.create - mac");
			if (createButtonTxt == "Create") {				
				gui.println("System::Creating ad-hoc network ...");
				String cmd = "open src/script/CreateAdhoc.app";
				run(cmd);
				
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					System.out.println("@Adhoc - InterruptedException: " + e.getMessage());
				}
				
				String myIP = getIP();
				cmd = "networksetup -setmanual Wi-Fi " + myIP + " 255.255.0.0";
				run(cmd);
				
				return 1;
			} else if (createButtonTxt == "Disconnect") { // disconnect
				gui.println("System::Disconnecting from ad-hoc network ...");
				String cmd = "open src/script/DisconnectAdhoc.app";
				run(cmd);
				
				cmd = "networksetup -setdhcp Wi-Fi";
				run(cmd);
				
				return 2;
			} else {
				gui.println("System Error::Non-functional Button");
				System.out.println("$$ IfMgt.create Error 7215: Create Button Error.");
			}
		}
		else if (OS.indexOf("windows") >= 0) {
			System.out.println("$$ IfMgt.create - windows");
			if (createButtonTxt == "Create") {
				gui.println("System::Creating ad-hoc network ...");
				try {
					new WinConnect(SSID, key);
				} catch (IOException e) {
					System.out.println("@Adhoc - IOException: " + e.getMessage());
				}
				return 1;
			} else if (createButtonTxt == "Disconnect") { // disconnect
				gui.println("System::Disconnecting from ad-hoc network ...");
				try {
					new WinDisconnect();
				} catch (IOException e) {
					System.out.println("@Adhoc - IOException: " + e.getMessage());
				}
				return 2;
			} else {
				gui.println("System Error::Non-functional Button.");
				System.out.println("$$ IfMgt.create Error 7216: Create Button Error.");
			}
		}
		else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0
				|| OS.indexOf("aix") > 0) {
			//TODO may need more dev work here
			System.out.println("$$ IfMgt.create - unix");
			String cmd = "sudo ifconfig wlan0 down; sudo dhclient -r wlan0; sudo ifconfig wlan0 up; sudo iwconfig wlan0 essid "
					+ SSID
					+ ";sudo iwconfig wlan0 mode Ad-Hoc; sudo dhclient wlan0";
			run(cmd);
		} else {
			System.out.println("$$ IfMgt.create - Error 7217: Needs implementation for current OS.");
			gui.println("System Error::Current OS not supported. Create to Ad-hoc network manually.");
		}
		return 0;
	}

	public int connect(String SSID, String key) {
		String OS = System.getProperty("os.name").toLowerCase();

		if (OS.indexOf("mac") >= 0) {
			String cmd = "networksetup -setairportnetwork en1 " + SSID + " " + key;
			run(cmd);
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				System.out.println("@Adhoc - InterruptedException: " + e.getMessage());
			}
			
			String myIP = getIP();
			cmd = "networksetup -setmanual Wi-Fi " + myIP + " 255.255.0.0";
			run(cmd);
		} else if (OS.indexOf("windows") >= 0) {
			gui.println("Connecting to ad-hoc network ...");
			try {
				new winConnecting();
			} catch (IOException e) {
				System.out.println("@Adhoc - IOException: wadConnection " + e.getMessage());
			}
		} else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0
				|| OS.indexOf("aix") > 0) {
			String cmd = "sudo ifconfig wlan0 down; sudo dhclient -r wlan0; sudo ifconfig wlan0 up; sudo iwconfig wlan0 essid "
					+ SSID
					+ "sudo iwconfig wlan0 mode Ad-Hoc; sudo dhclient wlan0";
			run(cmd);
		} else {
			System.out.println("$$ IfMgt.create - Error 7218: Needs implementation for current OS.");
			gui.println("System Error::Current OS not supported. Connect to Ad-hoc network manually.");
		}
		return 0;
	}

	// This will disconnect from the network
	public void disconnectNetwork() {
		String OS = System.getProperty("os.name").toLowerCase();

		if (OS.indexOf("mac") >= 0) {
			String cmd = "open src/script/DisconnectAdhoc.app";
			run(cmd);
			cmd = "networksetup -setdhcp Wi-Fi";
			run(cmd);
		} else if (OS.indexOf("windows") >= 0) {
			try {
				new WinDisconnect();
			} catch (IOException e) {
				System.out.println("@Adhoc - IOException: " + e.getMessage());
			}
		} else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0
				|| OS.indexOf("aix") > 0) {
			String cmd = "sudo ifconfig wlan0 down; sudo dhclient -r wlan0; sudo ifconfig wlan0 up";
			run(cmd);
		} else {
			gui.println("Current OS not supported. Connect to Ad-hoc network manually");
			System.out.println("IfMgt Error 4132: Needs implementation for current OS");
		}
		return;
	}

	void getOS() {
		String OS = System.getProperty("os.name").toLowerCase();

		System.out.println(OS);

		if (OS.indexOf("win") >= 0) { // is windows
			System.out.println("This is Windows");
		} else if (OS.indexOf("mac") >= 0) { // is mac
			System.out.println("This is Mac");
		} else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0
				|| OS.indexOf("aix") > 0) { // is unix
			System.out.println("This is Unix or Linux");
		} else {
			System.out.println("Your OS is not supported !!");
		}
	}

	// This is extra... I found out later that you already implemented - yannick
	// static void run ...
	static void runOSXcmd(String cmd) {
		Runtime run = Runtime.getRuntime();
		Process pr = null;

		try {
			pr = run.exec(cmd);
		} catch (IOException e) {
			System.out.println("@Adhoc - IOException: " + e.getMessage());
		}

		try {
			pr.waitFor();
		} catch (InterruptedException e) {
			System.out.println("@Adhoc - InterruptedException: " + e.getMessage());
		}

		BufferedReader buf = new BufferedReader(new InputStreamReader(
				pr.getInputStream()));
		String line = "";
		try {
			while ((line = buf.readLine()) != null) {
				System.out.println(line);
			}
		} catch (IOException e) {
			System.out.println("@Adhoc - IOException: " + e.getMessage());
		}
	}

	public static String getIP () {
		//Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
		Random randomGenerator = new Random();		
		String IP_Address = "10.10." + Integer.toString(randomGenerator.nextInt(253) + 1) + "." + Integer.toString(randomGenerator.nextInt(253) + 1);
		//max IP block is 254 because the broadcast address is 255
		
		return IP_Address;
	}
	
	public static int run(String cmd) {

		int exitVal = -1;
		try {
			Runtime rt = Runtime.getRuntime();
			Process pr = rt.exec(cmd);

			BufferedReader input = new BufferedReader(new InputStreamReader(
					pr.getInputStream()));
			String line = null;

			while ((line = input.readLine()) != null) {
				System.out.println(line);
			}

			exitVal = pr.waitFor();
			System.out.println("Exited with error code " + exitVal);

		} catch (Exception e) {
			System.out.println("@Adhoc - Exception: " + e.getMessage());
		}
		return exitVal;
	}
}
